package com.dream.io


import android.os.Build
import kotlinx.io.IOException
import kotlinx.io.files.Path
import java.io.File
import java.nio.file.Paths
import java.nio.file.Path as NioPath


fun Path.toFile(): File = File(this.toString())
fun SystemPath.toFile(): File = path.toFile()


fun NioPath.toKtPath(): Path = Path(this.toString())
fun File.toKtPath(): Path = Path(this.toString())

actual fun SystemPath.length(): Long {
    @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
    return path.file.length()
}

actual fun SystemPath.isDirectory(): Boolean {
    @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
    return path.file.isDirectory
}

actual fun SystemPath.isRegularFile(): Boolean {
    @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
    return path.file.isFile
}

actual val SystemPath.absolutePath: String
    @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
    get() = path.file.absolutePath

actual fun SystemPaths.createTempDirectory(
    prefix: String,
): SystemPath = kotlin.io.path.createTempDirectory(prefix = prefix).toKtPath().inSystem

actual fun SystemPaths.createTempFile(
    prefix: String,
    suffix: String
): SystemPath = kotlin.io.path.createTempFile(prefix = prefix, suffix = suffix).toKtPath().inSystem


@androidx.annotation.RequiresApi(Build.VERSION_CODES.O)
actual inline fun <T> SystemPath.useDirectoryEntries(block: (Sequence<SystemPath>) -> T): T {
    val directory = this.toFile() // 获取 File 对象

    if (!directory.exists()) {
        throw IOException("Directory does not exist: ${this.path}")
    }
    if (!directory.isDirectory) {
        throw IOException("Not a directory: ${this.path}")
    }

    val entries: List<SystemPath> = try {
        directory.listFiles()?.map {
            val path: Path = Paths.get(it.absolutePath).toKtPath()  // 创建 Path 对象
            SystemPath(path)                             // 创建 SystemPath 对象
        } ?: emptyList()
    } catch (e: SecurityException) {
        println("No permission to access directory: ${this.path}")
        emptyList() // Or throw an exception if appropriate
    }

    return block(entries.asSequence()) // 将结果转换为 Sequence 并传递给 block
}
